/*
 * @Author: nqx2007 fenglimima334@163.com
 * @Date: 2023-12-04 19:35:23
 * @LastEditors: nqx2007 fenglimima334@163.com
 * @LastEditTime: 2023-12-12 10:45:34
 * @FilePath: /operator-manager/src/components/RightContent/AvatarDropdown.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { logout } from '@/services';
import { loginPath } from '@/utils/globalConstants';
import { LogoutOutlined, UserOutlined } from '@ant-design/icons';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { history, useModel } from '@umijs/max';
import { Avatar, Spin } from 'antd';
import { stringify } from 'querystring';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback } from 'react';
import { flushSync } from 'react-dom';
import HeaderDropdown from '../HeaderDropdown';

export type GlobalHeaderRightProps = {
  menu?: boolean;
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = () => {
  /**
   * 退出登录，并且将当前的 url 保存
   */
  const toLoginOut = async () => {
    const result = await logout();
    if (result?.success) {
      //清除所有的本地存储
      localStorage.clear();
      //跳转到登录页面
      const { search, pathname } = window.location;
      const urlParams = new URL(window.location.href).searchParams;
      /** 此方法会跳转到 redirect 参数所在的位置 */
      const redirect = urlParams.get('redirect');
      // 头部字段有redirect会有安全风险，需要注意下一下
      if (window.location.pathname !== loginPath && !redirect) {
        history.replace({
          pathname: loginPath,
          search: stringify({
            redirect: pathname + search,
          }),
        });
      }
    }
  };
  // 用户菜单悬浮样式
  const actionClassName = useEmotionCss(({ token }) => {
    return {
      display: 'flex',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
      alignItems: 'center',
      padding: '0 8px',
      cursor: 'pointer',
      borderRadius: token.borderRadius,
      '&:hover': {
        backgroundColor: token.colorBgTextHover,
      },
    };
  });
  // 头像图标的样式
  const avatarClassName = useEmotionCss(({ token }) => {
    return {
      marginRight: '8px',
      verticalAlign: 'top',
      [`@media only screen and (max-width: ${token.screenMD}px)`]: {
        margin: 0,
      },
    };
  });
  // 名称显示的样式
  const nameClassName = useEmotionCss(({ token }) => {
    return {
      width: '70px',
      height: '48px',
      overflow: 'hidden',
      lineHeight: '48px',
      whiteSpace: 'nowrap',
      textOverflow: 'ellipsis',
      [`@media only screen and (max-width: ${token.screenMD}px)`]: {
        display: 'none',
      },
    };
  });
  // 获取当前的用户状态
  const { initialState, setInitialState } = useModel('@@initialState');

  // 用户菜单的点击回调
  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout') {
        flushSync(() => {
          setInitialState((s) => ({ ...s, currentUser: undefined }));
        });
        toLoginOut();
        return;
      }
    },
    [setInitialState],
  );

  // 没有获取到当前登录用户的时候的加载状态
  const loading = (
    <span className={actionClassName}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );
  if (!initialState || !initialState?.currentUser?.userName) {
    return loading;
  }
  const { currentUser } = initialState;
  const menuItems = [
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  return (
    <HeaderDropdown
      menu={{
        selectedKeys: [],
        onClick: onMenuClick,
        items: menuItems,
      }}
    >
      <span className={actionClassName}>
        <Avatar
          size="small"
          className={avatarClassName}
          icon={<UserOutlined />}
          alt="avatar"
        />
        <span className={`${nameClassName} anticon`}>
          {currentUser?.userName}
        </span>
      </span>
    </HeaderDropdown>
  );
};

export default AvatarDropdown;
